import XEUtils from 'xe-utils'
import store from '@/store'
import utils from '@common/utils/utils'

/**
 * 从菜单树中获取权限
 * @param datas 菜单树
 * @returns {{}} 权限对象：key为菜单sid，value为权限列表
 */
export const eachPermission = datas => {
    let permissionArr = {};
    datas.forEach(item => {
        if (item.child_count && item.child_count > 0) {
            let object = eachPermission(item.childrens);
            for (let key in object) {
                permissionArr[key] = (permissionArr[key] || []).concat(object[key]);
            }
        }
        if (item.res_type === 'button') {
            let list = permissionArr[item.parent_sid] || [];
            let sidList = list.map(sItem => sItem.sid);
            if (sidList.indexOf(item.sid) === -1) {
                list.push(item);
                permissionArr[item.parent_sid] = list;
            }
        }
    });
    return permissionArr;
};

/**
 * 检查权限
 * @param value
 * @param path
 * @returns {boolean}
 */
export const checkPermission = (value, path) => {
    const application = store.state.application
    let replaceBtnPermission = {}
    if (utils.isNotEmpty(application)) {
        const applicationStore = store.state[application]
        if (applicationStore && applicationStore.replaceBtnPermission) {
            replaceBtnPermission = applicationStore.replaceBtnPermission
        }
    }
    let routerMenu = store.getters.getMenuByPath(path)
    let permissionList = []
    if (XEUtils.isPlainObject(value) && utils.isNotEmpty(value.permission)) {
        permissionList = value.permission.split('|')
        if (utils.isNotEmpty(value.check_router)) {
            routerMenu = store.getters.getMenuByPath(value.check_router)
        }
    }
    if (XEUtils.isString(value) && utils.isNotEmpty(value)) {
        permissionList = value.split('|')
    }
    if (utils.isNotEmptyList(permissionList)) {
        permissionList = permissionList.map(p => replaceBtnPermission[p] ? replaceBtnPermission[p] : p)
    }
    let routePermission = (routerMenu.childrens || []).map(item => $.extend({}, item))
    if (utils.isNotEmptyList(routePermission)) {
        let filter = routePermission.filter(item => permissionList.indexOf(item.permission) !== -1)
        return utils.isNotEmptyList(filter)
    }
    return false
}
